from common.models.award_project import AwardProject
from common.models.award_detail import AwardDetail
from flask import Blueprint, request, make_response, redirect
from config.dingtalk_setting import AppKey, AppSecret, AgentId, role_hr, bpmid
from dingtalk import SecretClient, model
import json, requests
from application import app, db
from common.libs.DataHelper import getCurrentTime
import datetime
from common.libs.Helper import dingtalkpost
from config.dingtalk_setting import column
from common.models.user import User
from common.libs.SQLTransform import queryToDict

##连接
client = SecretClient(AppKey, AppSecret)  # 新 access_token 获取方式

award_page = Blueprint("award_page", __name__)


@award_page.route("/createproject", methods=['GET', 'POST'])
def createproject():
    form = request.json.get('form')
    b = request.json.get('b')
    floatsum = request.json.get('floatsum')
    floatnow = request.json.get('floatnow')
    creater = request.json.get('creater')
    user = request.json.get('user')
    print(form)

    try:
        award = AwardProject()
        award.user = user
        award.name = form['name']
        award.sn = form['sn']
        award.prefund = form['prefund']
        award.prefunddate = form['prefunddate']
        award.fund = form['fund']
        award.a = form['a']
        award.b = b
        award.k1 = form['k1']
        award.k2 = form['k2']
        award.k3 = form['k3']
        award.floatraito = form['floatraito']
        award.floatsum = floatsum
        award.floatnow = floatnow
        award.creater = creater
        award.status = 0
        award.updated_time = award.created_time = getCurrentTime()
        db.session.add(award)
        db.session.commit()
        id = award.id
    except Exception as e:
        print(e)
        return json.dumps({"msg": "项目基础资料信息不全，请检查是否有漏填", "code": 401}, ensure_ascii=False)
    else:
        return json.dumps({"msg": "项目基础资料录入成功", "code": 200, "id": id}, ensure_ascii=False)


@award_page.route("/adddetail", methods=['GET', 'POST'])
def adddetail():
    form = request.json.get('form')
    id = request.json.get('id')
    user = request.json.get('user')
    nowfund = request.json.get('nowfund')
    afterfund = request.json.get('afterfund')
    detailfund = request.json.get('detailfund')
    print(request.json)
    try:
        award = AwardDetail()
        award.projectid = id
        award.name = user
        award.role = form['role']
        award.detailraito = form['detailraito']
        award.nowfund = nowfund
        award.afterfund = afterfund
        award.detailfund = detailfund
        db.session.add(award)
        db.session.commit()
    except Exception as e:
        print(e)
        return json.dumps({"msg": "信息不全，请检查是否有漏填", "code": 401}, ensure_ascii=False)
    else:
        user = User.query.filter_by(id=user).first()
        name = user.name
        return json.dumps(
            {"msg": "录入成功", "code": 200, 'name': name, 'role': form['role'], 'detailraito': form['detailraito'],
             'nowfund': nowfund, 'afterfund': afterfund, 'detailfund': detailfund}, ensure_ascii=False)


@award_page.route("/editdetail", methods=['GET', 'POST'])
def editdetail():
    form = request.json.get('form')
    nowfund = request.json.get('nowfund')
    afterfund = request.json.get('afterfund')
    detailfund = request.json.get('detailfund')
    print(request.json)

    try:
        award = AwardDetail.query.filter_by(id=form['id']).first()
        award.projectid = form['projectid']
        # award.name = form['userid']
        # award.role = form['role']
        award.detailraito = form['detailraito']
        award.nowfund = nowfund
        award.afterfund = afterfund
        award.detailfund = detailfund
        db.session.commit()
    except Exception as e:
        print(e)
        return json.dumps({"msg": "信息不全，请检查是否有漏填", "code": 401}, ensure_ascii=False)
    else:
        return json.dumps(
            {"msg": "修改成功", "code": 200, 'name': form['name'], 'role': form['role'], 'detailraito': form['detailraito'],
             'nowfund': nowfund, 'afterfund': afterfund, 'detailfund': detailfund}, ensure_ascii=False)


@award_page.route("/getprojectlist", methods=['GET', 'POST'])
def getprojectlist():
    userid = request.json.get('id')

    priject = AwardProject.query.filter_by(creater=userid).order_by(AwardProject.created_time.desc()).all()

    rts = []
    for item in priject:
        temp = dict(id=item.id, name=item.name, sn=item.sn, created_time=str(item.created_time),
                    username=item.username.name, status=item.status)
        rts.append(temp)

    return json.dumps(rts, ensure_ascii=False)


@award_page.route("/searchproject", methods=['GET', 'POST'])
def searchproject():
    userid = request.json.get('id')
    type = request.json.get('type')
    content = request.json.get('content')
    if content == "":
        priject = AwardProject.query.filter_by(creater=userid).order_by(
            AwardProject.created_time.desc()).all()

        rts = []
        for item in priject:
            temp = dict(id=item.id, name=item.name, sn=item.sn, created_time=str(item.created_time),
                        username=item.username.name, status=item.status)
            rts.append(temp)


    else:
        if type == "项目名称":
            priject = AwardProject.query.filter_by(creater=userid).filter_by(name=content).order_by(
                AwardProject.created_time.desc()).all()

            rts = []
            for item in priject:
                temp = dict(id=item.id, name=item.name, sn=item.sn, created_time=str(item.created_time),
                            username=item.username.name, status=item.status)
                rts.append(temp)


        else :
            priject = AwardProject.query.filter_by(creater=userid).filter_by(sn=content).order_by(
                AwardProject.created_time.desc()).all()

            rts = []
            for item in priject:
                temp = dict(id=item.id, name=item.name, sn=item.sn, created_time=str(item.created_time),
                            username=item.username.name, status=item.status)
                rts.append(temp)

    return json.dumps(rts, ensure_ascii=False)


@award_page.route('/getdetail', methods=['GET', 'POST'])
def getdetail():
    id = request.args.get('id')
    awardproject = AwardProject.query.filter_by(id=id).all()
    projectinfo = queryToDict(awardproject)
    del projectinfo[0]['updated_time']
    del projectinfo[0]['created_time']
    awarddetail = AwardDetail.query.filter_by(projectid=id).all()
    print(projectinfo)

    user = User.query.filter_by(id=projectinfo[0]['creater']).first()

    # userinfo = dict(label=user.name, value=user.userid, key=user.id)

    detail = []
    for item in awarddetail:
        temp = dict(id=item.id, name=item.username.name, userid=item.name, role=item.role, detailraito=item.detailraito,
                    detailfund=item.detailfund, nowfund=item.nowfund,
                    afterfund=item.afterfund, projectid=item.projectid,
                    )
        detail.append(temp)
    print(detail)
    res = {"projectinfo": projectinfo, "detail": detail, "username": user.name}
    return json.dumps(res, ensure_ascii=False)


@award_page.route('/addpost', methods=['GET', 'POST'])
def addpost():
    form = request.json.get('form')
    b = request.json.get('b')
    floatsum = request.json.get('floatsum')
    floatnow = request.json.get('floatnow')
    creater = request.json.get('creater')

    detailtableform = request.json.get('detailtableform')

    user = request.json.get('user')
    userquery = User.query.filter_by(id=user).first()
    username = userquery.name
    dept_id = userquery.depid

    projectid = request.json.get('projectid')

    fileinfo = request.json.get("fileinfo")

    detaillist = []
    for item in detailtableform:
        temp = [{'name': '人员姓名', 'value': item['name']}, {'name': '人员角色', 'value': item['role']},
                {'name': '浮动占比', 'value': item['detailraito']}, {'name': '浮动金额', 'value': item['detailfund']},
                {'name': '当月兑现', 'value': item['nowfund']}, {'name': '回款发放', 'value': item['afterfund']}, ]

        # temp = dict(人员姓名=item.name, 人员角色=item.role, 浮动占比=item.detailraito, 浮动金额=item.detailfund,
        #             当月兑现=item.nowfund,回款发放=item.afterfund)
        detaillist.append(temp)

    form_component_values = [
        {
            'name': '系统编号', 'value': projectid
        },

        {
            'name': '项目编号', 'value': form['sn']
        },
        {
            'name': '项目名称', 'value': form['name']
        },
        {
            'name': '项目负责人', 'value': username
        },
        {
            'name': '预收款到账金额', 'value': form['prefund']
        },

        {
            'name': '预收款到账时间', 'value': str(form["prefunddate"])[:10]
        },

        {
            'name': '合同金额', 'value': form['fund']
        },

        {
            'name': '准签线价格', 'value': form['a']
        },

        {
            'name': '贡献毛利数', 'value': b
        },

        {
            'name': '回款系数', 'value': form['k1']
        },

        {
            'name': '质保金系数', 'value': form['k2']
        },

        {
            'name': '质保期系数', 'value': form['k3']
        },

        {
            'name': '浮动工资总额', 'value': floatsum
        },

        {
            'name': '浮动比例', 'value': form['floatraito']
        },

        {
            'name': '本月浮动金额', 'value': floatnow
        },

        {
            "name": "浮动工资分配明细",
            "value": detaillist
        },

        {
            "name": "附件",
            "value": fileinfo
        },
    ]

    process_code = bpmid["浮动工资"]

    dingtalksn = client.bpms.processinstance_create(agent_id=AgentId, form_component_values=form_component_values,
                                                    process_code=process_code, originator_user_id=creater,
                                                    dept_id=dept_id)
    awardporject = AwardProject.query.filter_by(id=projectid).first()
    awardporject.status = 1
    db.session.commit()

    return json.dumps({"msg": "发起审批成功", "code": 200}, ensure_ascii=False)


@award_page.route('/editpost', methods=['GET', 'POST'])
def editpost():
    form = request.json.get('form')
    b = request.json.get('b')
    floatsum = request.json.get('floatsum')
    floatnow = request.json.get('floatnow')
    creater = request.json.get('creater')

    detailtableform = request.json.get('detailtableform')

    userquery = User.query.filter_by(userid=creater).first()
    dept_id = userquery.depid

    projectid = request.json.get('projectid')

    fileinfo = request.json.get("fileinfo")

    detaillist = []
    for item in detailtableform:
        temp = [{'name': '人员姓名', 'value': item['name']}, {'name': '人员角色', 'value': item['role']},
                {'name': '浮动占比', 'value': item['detailraito']}, {'name': '浮动金额', 'value': item['detailfund']},
                {'name': '当月兑现', 'value': item['nowfund']}, {'name': '回款发放', 'value': item['afterfund']}, ]

        # temp = dict(人员姓名=item.name, 人员角色=item.role, 浮动占比=item.detailraito, 浮动金额=item.detailfund,
        #             当月兑现=item.nowfund,回款发放=item.afterfund)
        detaillist.append(temp)

    form_component_values = [
        {
            'name': '系统编号', 'value': projectid
        },

        {
            'name': '项目编号', 'value': form['sn']
        },
        {
            'name': '项目名称', 'value': form['name']
        },
        {
            'name': '项目负责人', 'value': form['username']
        },
        {
            'name': '预收款到账金额', 'value': form['prefund']
        },

        {
            'name': '预收款到账时间', 'value': str(form["prefunddate"])[:10]
        },

        {
            'name': '合同金额', 'value': form['fund']
        },

        {
            'name': '准签线价格', 'value': form['a']
        },

        {
            'name': '贡献毛利数', 'value': b
        },

        {
            'name': '回款系数', 'value': form['k1']
        },

        {
            'name': '质保金系数', 'value': form['k2']
        },

        {
            'name': '质保期系数', 'value': form['k3']
        },

        {
            'name': '浮动工资总额', 'value': floatsum
        },

        {
            'name': '浮动比例', 'value': form['floatraito']
        },

        {
            'name': '本月浮动金额', 'value': floatnow
        },

        {
            "name": "浮动工资分配明细",
            "value": detaillist
        },

        {
            "name": "附件",
            "value": fileinfo
        },
    ]

    process_code = bpmid["浮动工资"]

    dingtalksn = client.bpms.processinstance_create(agent_id=AgentId, form_component_values=form_component_values,
                                                    process_code=process_code, originator_user_id=creater,
                                                    dept_id=dept_id)
    awardporject = AwardProject.query.filter_by(id=projectid).first()
    awardporject.status = 1
    db.session.commit()

    return json.dumps({"msg": "重新审批成功", "code": 200}, ensure_ascii=False)


# 同意后
@award_page.route('/bpmagree', methods=['GET', 'POST'])
def bpmagree():
    res = request.values.to_dict()
    processInstanceId = res['processInstanceId']
    content = {
        "process_instance_id": processInstanceId
    }
    url = "https://oapi.dingtalk.com/topapi/processinstance/get"
    bpminfo = dingtalkpost(url=url, content=content)
    content = bpminfo['process_instance']['form_component_values']

    projectid = content[0]['value']
    awardproject = AwardProject.query.filter_by(id=projectid).first()
    awardproject.status = 2
    db.session.commit()
    return json.dumps("info", ensure_ascii=False)


# 不同意后
@award_page.route('/bpmrefuse', methods=['GET', 'POST'])
def bpmrefuse():
    res = request.values.to_dict()
    processInstanceId = res['processInstanceId']
    content = {
        "process_instance_id": processInstanceId
    }
    url = "https://oapi.dingtalk.com/topapi/processinstance/get"
    bpminfo = dingtalkpost(url=url, content=content)
    content = bpminfo['process_instance']['form_component_values']
    # userid = content[1]['value']
    projectid = content[0]['value']
    awardproject = AwardProject.query.filter_by(id=projectid).first()
    awardproject.status = 3
    db.session.commit()
    return json.dumps("info", ensure_ascii=False)


@award_page.route('/deletedetail', methods=['GET', 'POST'])
def deletedetail():
    id = request.json.get('id')
    awarddetail = AwardDetail.query.filter_by(id=id).delete()
    db.session.commit()
    return json.dumps({"msg": "人员明细已删除"}, ensure_ascii=False)


@award_page.route('/deleteproject', methods=['GET', 'POST'])
def deleteproject():
    id = request.json.get('id')
    awardproject = AwardProject.query.filter_by(id=id).delete()
    awarddetail = AwardDetail.query.filter_by(projectid=id).delete()
    db.session.commit()
    return json.dumps({"msg": "已整单作废"}, ensure_ascii=False)
